<!--
 * @Description: 
 * @Author: Gaq
 * @Date: 2022-10-19 17:31:35
 * @LastEditTime: 2022-11-29 20:03:01
 * @LastEditors: Gaq
-->
<script setup>
import request from "@/utils/request";
import router from "@/router";
import { useRoute } from "vue-router";
import bus from "vue3-eventbus";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";

const { state, commit } = useStore();
let userId = computed(() => state.userId);
let num = ref(1);
let route = useRoute();
const goodId = Number(route.query.goodId);
let goodObj = ref({});
let styleList = ref([]);
let collectionList = [];
let status = ref(true);
let deleteId = ref();
const collection = {
  userId: userId.value,
  goodsId: "",
  name: "",
  image: "",
  price: "",
};
// 默认显示评价页面
const activeName = ref("second");
// 评价选择数量
const radio = ref(1);
const value = ref("推荐排序");
let noClick = ref(true);

onBeforeMount(() => {
  if (localStorage.getItem("user")) {
    commit("SET_USERID", JSON.parse(localStorage.getItem("user")).userId);
    getCollectionList();
  }
  request.get(`/goods/getOne/${goodId}`).then((res) => {
    goodObj.value = res.data;
    passData(goodId);
  });
  request.get(`/style/getPart/${goodId}`).then((res) => {
    styleList.value = res.data;
    console.log(styleList.value);
  });
});

const passData = (value) => {
  bus.emit("provideEvaluateData", value);
};

const handleClick = (tab, event) => {
  // console.log(tab, event)
};

const options = [
  {
    value: "推荐排序",
    label: "推荐排序",
  },
  {
    value: "时间排序",
    label: "时间排序",
  },
];

const getCollectionList = () => {
  request
    .get(`/collection/getPart/${userId.value}`)
    .then((res) => {
      collectionList = res.data;
    })
    .then(() => {
      if (collectionList !== null) {
        collectionList.some((i) => {
          if (i.goodsId === goodObj.value.goodsId) {
            status.value = false;
            // 将good在收藏表中的id存储起来，为取消收藏做准备
            deleteId.value = i.colId;
            return true;
          }
        });
      }
    });
};

const getGoodData = () => {
  collection.goodsId = goodObj.value.goodsId;
  collection.name = goodObj.value.introduction;
  collection.image = goodObj.value.cover;
  collection.price = goodObj.value.coverPrice;
};

const addCollection = () => {
  getGoodData();
  userId.value
    ? (request.post(`/collection/insertOne`, collection).then((res) => {
        if (res.code == 0) {
          status.value = false;
          ElMessage.success("收藏成功");
        }
      }),
      getCollectionList())
    : ElMessage.error("请先登录");
};
const deleteCollection = () => {
  getCollectionList();
  request.delete(`/collection/deleteOne/${deleteId.value}`).then((res) => {
    if (res.code == 0) {
      status.value = true;
      ElMessage.success("取消收藏");
    }
  });
};
let cart = {
  userId: userId.value,
  goodsId: goodId,
  styleId: "",
  image: "",
  name: "",
  styleName: "",
  num: 1,
};
const addCart = () => {
  if (userId.value) {
    if (isClick.value == -1) {
      ElMessage.warning("请选择款式");
    } else {
      getNum(num.value);
      request.get(`/cart/getPart/${userId.value}`).then((res) => {
        if (res.code == 0) {
          const result = res.data.find((item) => {
            if (item.goodsId == cart.goodsId && item.styleId == cart.styleId) {
              return item;
            }
          });
          result
            ? ((cart.cartId = result.cartId),
              (cart.num += result.num),
              request.put("/cart/updateOne", cart).then((res) => {
                if (res.code == 0) {
                  ElMessage.success("加入购物车成功");
                }
              }))
            : request.post("/cart/insertOne", cart).then((res) => {
                ElMessage.success("加入购物车成功");
              });
        } else {
          request.post("/cart/insertOne", cart).then((res) => {
            res.code == 0
              ? ElMessage.success("加入购物车成功")
              : ElMessage.error(res.msg);
          });
        }
      });
    }
  } else {
    ElMessage.error("请先登录");
  }
};

// 用户选择的样式
let isClick = ref(-1);
const showName = (value) => {
  cart.name = toRaw(goodObj.value).introduction;
  cart.image = value.styleImage;
  cart.styleName = value.styleName;
  cart.styleId = value.styleId;
  // passOrderData(cart);
};
const confirmStyle = (value) => {
  value.styleStock == 0
    ? ElMessage.warning("该款式暂无库存，请选择其他款式~")
    : (isClick.value = value.styleId);
};
const getNum = (num) => {
  cart.num = num;
};
// 立即购买
/* const passOrderData = (value) => {
  bus.emit("orderDetail", value);
}; */
let order = {};
const goOrder = () => {
  if (userId.value) {
    if (isClick.value == -1) {
      ElMessage.warning("请选择商品信息");
    } else {
      router.push("/order");
      router.beforeEach((to, from, next) => {
        cart.price = goodObj.value.coverPrice;
        localStorage.setItem(
          "orderDetail",
          encodeURIComponent(JSON.stringify(cart))
        );
        next();
      });
    }
  } else {
    ElMessage.error("请先登录");
  }
};
let clickId = ref(1); //用户点击的radio的编号
const filterEvaluate = (value) => {
  clickId.value = value;
};
let selectValue = ref("推荐排序");
const selectVal = (value) => {
  selectValue.value = value;
};
</script>

<template>
  <div class="container">
    <div class="box1">
      <div class="block text-center imgHome" m="t-4" style="width: 650px">
        <el-carousel trigger="click" height="300px" :interval="3000">
          <el-carousel-item v-for="item in 4" :key="item">
            <img
              :src="goodObj.cover"
              :alt="goodObj.sort"
              style="width: 100%; height: 100%"
            />
          </el-carousel-item>
        </el-carousel>
      </div>
      <div class="infoBox">
        <!-- <h3>{{ goodObj.sort }}</h3> -->
        <h3>{{ goodObj.introduction }}</h3>
        <div>
          <span style="font-size: x-large; color: red; font-weight: 800"
            >￥{{ goodObj.coverPrice }}</span
          ><br /><!-- 优惠&nbsp;&nbsp;
          <span>满二百减二十</span> -->
        </div>
        <span style="font-size: small">
          发货地&nbsp;浙江金华 快递&nbsp;&nbsp;免运费
          &nbsp;&nbsp;&nbsp;&nbsp;付款后十五天内发货
        </span>
        <div class="style">
          <div
            style="
              color: grey;
              font-size: small;
              display: flex;
              line-height: 25px;
            "
          >
            <p>款式&nbsp;&nbsp;</p>
            <div
              @click="confirmStyle(styleItem)"
              v-for="styleItem in styleList"
              style="border: 1px solid rgb(210, 210, 210); margin-left: 5px"
              :class="isClick == styleItem.styleId ? 'addClass' : ''"
            >
              <p :title="styleItem.styleName" @click="showName(styleItem)">
                {{ styleItem.styleName }}
              </p>
            </div>
          </div>
        </div>
        <div style="color: grey; font-size: small; display: flex">
          <p>数量&nbsp;&nbsp;</p>
          <el-input-number
            v-model="num"
            :min="1"
            :max="10"
            size="small"
            @change="getNum(num)"
          />
          <div
            class="collectionBtn"
            v-if="status"
            @click="$noMulClicks(addCollection)"
          >
            <el-icon :size="19"><i-ep-Star /></el-icon>
            <p>收藏</p>
          </div>
          <div
            class="collectionBtn"
            v-if="!status"
            @click="$noMulClicks(deleteCollection)"
          >
            <el-icon :size="21"><i-ep-StarFilled color="gold" /></el-icon>
            <p>收藏</p>
          </div>
        </div>
        <div class="btnShop">
          <button
            style="background-color: rgb(255, 228, 208); color: rgb(242, 45, 0)"
            @click="$noMulClicks(goOrder)"
          >
            立即购买
          </button>
          <button
            style="background-color: rgb(242, 45, 0)"
            @click="$noMulClicks(addCart)"
          >
            <span><i-ep-ShoppingCart /></span>加入购物车
          </button>
        </div>
      </div>
    </div>
    <div class="detailBox">
      <el-tabs
        stretch
        v-model="activeName"
        type="border-card"
        class="demo-tabs"
        @tab-click="handleClick"
      >
        <el-tab-pane label="详情" name="first">商品详情</el-tab-pane>
        <el-tab-pane label="评价" name="second">
          <div class="optionBox">
            <el-radio-group v-model="radio" @change="filterEvaluate(radio)">
              <el-radio :label="1">全部</el-radio>
              <el-radio :label="3">好评</el-radio>
              <el-radio :label="5">中评</el-radio>
              <el-radio :label="7">差评</el-radio>
            </el-radio-group>
            <div class="selectBox">
              <el-select
                v-model="value"
                class="m-2"
                placeholder="Select"
                size="small"
                @change="selectVal"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div>
          <UserEvaluate
            :clickId="clickId"
            :selectVal="selectValue"
          ></UserEvaluate>
        </el-tab-pane>
        <el-tab-pane label="服务" name="third"
          >划线价格<br />
          指商品的专柜价、吊牌价、正品零售价、厂商指导价或该商品的曾经展示过的销售价等，并非原价，仅供参考。<br />
          未划线价格<br />
          指商品的实时标价，不因表述的差异改变性质。具体成交价格根据商品参加活动，或会员使用优惠券、积分等发生变化，最终以订单结算页价格为准。<br />
          商家详情页（含主图）以图片或文字形式标注的一口价、促销价、优惠价等价格可能是在使用优惠券、满减或特定优惠活动和时段等情形下的价格，具体请以结算页面的标价、优惠条件或活动规则为准。
          此说明仅当出现价格比较时有效，具体请参见《淘宝价格发布规范》。若商家单独对划线价格进行说明的，以商家的表述为准。</el-tab-pane
        >
      </el-tabs>
    </div>
  </div>
</template>

<style lang="less" scoped>
.container {
  width: 100vh;
  margin: 10px auto;
}
.box1 {
  display: flex;
}
.infoBox {
  .box1();
  flex-direction: column;
  justify-content: space-evenly;
  margin-left: 20px;
}
.collectionBtn {
  width: 60px;
  margin-left: 20px;
  display: flex;
  vertical-align: middle;
  p {
    user-select: none;
    font-size: 15px;
    margin-left: 3px;
  }
}
.collectionBtn:hover {
  cursor: pointer;
  border-radius: 5px;
  background-color: #dfe2e7;
}
.btnShop {
  .box1();
  button {
    cursor: pointer;
    border: none;
    color: white;
    border-radius: 5%;
    outline: none;
    margin-right: 30px;
    width: 130px;
    height: 30px;
    span {
      vertical-align: middle;
    }
  }
}
.style {
  p {
    height: 25px;
    line-height: 25px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  p:hover {
    cursor: pointer;
  }
}
.addClass {
  border-color: rgb(90, 204, 239);
  color: rgb(90, 204, 239);
}

.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.detailBox {
  margin-top: 60px;
  width: 720px;
}
.optionBox {
  border: 1px solid rgb(217, 218, 220);
  width: 712px;
  height: 35px;
  line-height: 35px;
  margin-left: -15px;
  padding-left: 5px;
  background-color: rgb(252, 252, 252);
}

.selectBox {
  float: right;
  margin-right: 6px;
  width: 100px;
  line-height: 35px;
  select {
    border: 1px solid rgb(217, 218, 220);
  }
}
select:focus-visible {
  outline: none;
}
</style>